// 储存数据
export const setItem = (key, value, exp = 0) => {
	if (checkKey(key)) {
		if (typeof key !== 'string' || !key) {
			// return 'key不存在,或者不是字符串'
			console.log('key不存在,或者不是字符串')
			return false
		}

		if (exp > 0) {
			// 时间设置
			exp = exp * 24 * 60 * 60 * 1000 + new Date().getTime()
		} else {
			exp = 0
		}

		let obj = {
			exp: exp,
			value: value
		}
		try {
			uni.setStorageSync(key, JSON.stringify(obj))
			return true
		} catch (e) {
			return false
		}
	}
}
// 获取储存数据
export const getItem = (key) => {
	if (checkKey(key)) {
		try {
			const value = uni.getStorageSync(key)
			console.log(key,'Storage')
			if (value) {
				// 看过没过期
				let obj = JSON.parse(value)
				// 永久存储
				if (obj.exp === 0) {
					return obj.value
				} else if(obj.exp>new Date().getTime()){
					return obj.value
				}else{
					console.log('缓存已经到期了')
					remove(key)
					return false
				}

			} else {
				console.log('没有当前缓存')
				return false
			}
		} catch (e) {
			console.log('错啦')
			return false
		}
	}
}
// 移除
export const remove = (key) => {
	if (checkKey(key)) {
		try {
			uni.removeStorageSync(key)
			return true
		} catch (e) {
			return false
		}
	}
}
// 全部清空
export const clear = () => {
	try {
		uni.clearStorageSync()
		return true
	} catch (e) {
		//TODO handle the exception
		return false
	}
}

// 判断过期
const checkKey = (key)=> {
	if (typeof key !== 'string' || !key) {
		console.log('key不是一个字符串')
		return false
	}
	return true
}